package com.deYang.app.ljodfh.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.JsonArray;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.deYang.app.ljodfh.R;
import com.deYang.app.ljodfh.base.BaseActivity;
import com.deYang.app.ljodfh.base.Constances;
import com.deYang.app.ljodfh.beans.FUsers;
import com.deYang.app.ljodfh.beans.SingleResult;
import com.deYang.app.ljodfh.http.AbsNetCallBack;
import com.deYang.app.ljodfh.http.NetUtils;
import com.deYang.app.ljodfh.http.ParamsEditor;
import com.deYang.app.ljodfh.ui.adapter.RebllionCommitAdapter;
import com.deYang.app.ljodfh.ui.dialog.PicChoiceDiaFragment;
import com.deYang.app.ljodfh.ui.dialog.RebllionDiaFragment;
import com.deYang.app.ljodfh.ui.dialog.ShotChoiceDiaFragment;
import com.deYang.app.ljodfh.ui.fragment.RebllionFragment;
import com.deYang.app.ljodfh.ui.utils.PermissionUtils;
import com.deYang.app.ljodfh.ui.utils.PictureUtils;
import com.deYang.app.ljodfh.ui.utils.TitleUtils;
import com.deYang.app.ljodfh.ui.utils.UiListMarginUtils;
import com.deYang.app.ljodfh.utils.UserManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.deYang.app.ljodfh.base.Constances.REBLLION_KEY;
import static com.deYang.app.ljodfh.base.Constances.SITE_ID;

public class RebllionCommitActivity extends BaseActivity implements RebllionCommitAdapter.RemainListSize, TextWatcher {
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView publish;
    @BindView(R.id.rebllion_commit_content)
    protected CustomFontEditText rebllion_commit;
    @BindView(R.id.rebllion_commit_type_title)
    protected CustomFontTextView type_cv;
    @BindView(R.id.rebllion_commit_address_title)
    protected CustomFontTextView addree_cv;
    @BindView(R.id.rebllion_commit_pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.rebllion_commit_prompt)
    protected CustomFontTextView prompt;

    private RebllionDiaFragment rebllionDiaFragment;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    private RebllionCommitAdapter adapter;
    private GridLayoutManager manger;
    private List<LocalMedia> selectList = new ArrayList<>();

    private Handler mHandler;
    private int maxSelectNum = 9;
    private int type = TYPE_CAMERA_PIC;  //type为0 拍照 1 录像 2图片
    private int rebellionType = Constances.REBELLION_TYPE_BREAKING_NEWS;
    private List<LocalMedia> currentList = new ArrayList<>();
    private int themeId;
    private boolean isLongClick = true;
    private String mVideoCoverImage;
    private int mLocationState = 0; //0正在定位，1定位成功，2定位失败
    private long mLocationTime = 0;
    private LocationClient mLocationClient = null;
    private BDLocationListener mLocationListener = new MyLocationListener();
    private PermissionUtils mPermissionUtils;
    public static final int REQUEST_CODE = 8;
    public static final String REBLLION_TAG = "dia_rebllion_fragment";
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    public static final int TYPE_CAMERA_PIC = 0;
    public static final int TYPE_VIDEO = 1;
    public static final int TYPE_PIC = 2;
    private String coverImageUrl;
    private JsonArray images;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        themeId = R.style.picture_default_style;
        mHandler = new Handler();
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_rebllion_commit);
        ButterKnife.bind(this);
    }

    private void initView() {
        publish.setVisibility(View.VISIBLE);
        publish.setText(getString(R.string.rebllion_publish));
        publish.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        manger = new GridLayoutManager(this, 3);
        pic_list.setItemAnimator(new DefaultItemAnimator());
        manger.setSmoothScrollbarEnabled(true);
        manger.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        pic_list.setLayoutManager(manger);
        new UiListMarginUtils().setMargin(this, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
        int type = getIntent().getIntExtra(RebllionFragment.EX_TYPE, -1);
        if (type > 0) {
            selectList = (ArrayList<LocalMedia>) getIntent().getSerializableExtra(EX_DATA);
            if (selectList != null) {
                currentList.addAll(selectList);
            }
            prompt.setVisibility(View.GONE);
        }
        adapter = new RebllionCommitAdapter(this, selectList).setItemInternalClick(picItemClick).setRemainListSize(this);
        adapter.setOnLongItemClick(onLongClick);
//        adapter.setList(selectList);
//        adapter.setSelectMax(maxSelectNum);
        pic_list.setAdapter(adapter);
        rebllion_commit.addTextChangedListener(this);
        rebellionType = (int) SharedPreferencesUtil.getParam(this, REBLLION_KEY, 1);
        refreshRebellionType();
        refreshLocationState(null);
        checkLocationPermission();

    }

    @OnClick(value = {R.id.rebllion_commit_type, R.id.title_top_edit, R.id.rebllion_commit_address_title})
    public void rebllionClick(View view) {
        switch (view.getId()) {
            case R.id.rebllion_commit_type:
                if (rebllionDiaFragment == null) {
                    rebllionDiaFragment = new RebllionDiaFragment();
                }
                rebllionDiaFragment.setCallBack(rebllionCallback);
                rebllionDiaFragment.show(getSupportFragmentManager(), REBLLION_TAG);
                break;
            case R.id.title_top_edit:
                if (UserManager.getInstance().isLogin()) {
                    if (TextUtils.isEmpty(rebllion_commit.getText().toString())) {
                        toast(R.string.rebllion_publish_content_empty);
                        return;
                    }
                    if (rebellionType == Constances.REBELLION_TYPE_PIC_NEWS && (!ListUtils.isListValued(currentList) || PictureMimeType
                            .pictureToVideo(currentList.get(0).getPictureType()) != 1)) {
                        toast(R.string.rebllion_publish_img_empty);
                        return;
                    }
                    if (rebellionType == Constances.REBELLION_TYPE_VIDEO_NEWS && (!ListUtils.isListValued(currentList) || PictureMimeType
                            .pictureToVideo(currentList.get(0).getPictureType()) != 2)) {
                        toast(R.string.rebllion_publish_video_empty);
                        return;
                    }
//                if (mLocationState == 0) {
//                    toast(R.string.rebllion_publish_toast_locating);
//                    return;
//                }
//                if (mLocationState == 2) {
//                    toast(R.string.rebllion_publish_toast_locating_falied);
//                    return;
//                }
                    uploadData();
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.rebllion_commit_address_title:
                if (mLocationState == 0) {
//                    initLocation();
//                    getLocation();
                    checkLocationPermission();
                } else if (mLocationState == 2) {
                    checkLocationPermission();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Log.e("path", "==pic==" + selectList.toString() + selectList.size() + type);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    if (type == TYPE_CAMERA_PIC) {
                        currentList.addAll(selectList);
                        selectList = currentList;
                        if (adapter.getEqualDatas() == selectList) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.setData(selectList);
                        }
                    } else if (type == TYPE_VIDEO) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);
                    } else if (type == TYPE_PIC) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);
                    }
                    break;
                case REQUEST_CODE:
                    int pos = data.getIntExtra(PictureExternalPreviewActivity.POS, 0);
                    if (pos > 0) {
                        selectList = (List<LocalMedia>) data.getSerializableExtra(PictureExternalPreviewActivity.PIC_LIST);
                        adapter.setData(selectList);
                    } else {
                        adapter.clean();
                        selectList.clear();
                    }
                    break;
            }
        }
    }

    private void getShotDiaFragment() {
        if (shotChoiceDiaFragment == null) {
            shotChoiceDiaFragment = new ShotChoiceDiaFragment();
        }
        shotChoiceDiaFragment.setCallBack(shotCallBack);
        shotChoiceDiaFragment.show(getSupportFragmentManager(), SHOT_TAG);
    }

    private BaseDialogFragment.ICallBack rebllionCallback = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            rebellionType = msg.what;
            // shotChoiceDiaFragment.dismiss();
            refreshRebellionType();
        }
    };

    private void refreshRebellionType() {
        switch (rebellionType) {
            case Constances.REBELLION_TYPE_BREAKING_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_one));
                break;
            case Constances.REBELLION_TYPE_EXPERIENCES:
                type_cv.setText(getString(R.string.rebllion_type_two));
                break;
            case Constances.REBELLION_TYPE_HOT_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_three));
                break;
            case Constances.REBELLION_TYPE_PIC_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_four));
                break;
            case Constances.REBELLION_TYPE_VIDEO_NEWS:
                type_cv.setText(getString(R.string.rebllion_type_five));
                break;
        }
    }

    BaseDialogFragment.ICallBack picCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                if (selectList.size() != 0) {
                    int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                    if (pictureType == 2 && selectList.size() == 1) {
                        toast("只能选择一个视频");
                    } else {
                        getShotDiaFragment();
                    }
                } else {
                    getShotDiaFragment();
                }
            } else if (msg.what == 2) {
                type = TYPE_PIC;
                PictureUtils.choicePic(RebllionCommitActivity.this, themeId, selectList);
            }
        }
    };
    BaseDialogFragment.ICallBack shotCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                type = TYPE_CAMERA_PIC;
                PictureUtils.choicePhoto(RebllionCommitActivity.this);
            } else if (msg.what == 2) {
                type = TYPE_VIDEO;
                if (selectList != null) {
                    selectList.clear();
                }
                PictureUtils.choiceVideo(RebllionCommitActivity.this);
            }
        }
    };
    OnItemInternalClick picItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (selectList == null) {
                return;
            }
            if (position == adapter.getItemCount() - 1) {
                if (selectList.size() < 9) {
                    if (picChoiceDiaFragment == null) {
                        picChoiceDiaFragment = new PicChoiceDiaFragment();
                    }
                    picChoiceDiaFragment.setCallBack(picCallBack);
                    if (!picChoiceDiaFragment.isShowing()) {
                        picChoiceDiaFragment.show(getSupportFragmentManager(), PIC_TAG);
                    }
                    prompt.setVisibility(View.GONE);
                } else {
                    toast(getString(R.string.rebllion_publish_pic_total));
                }

            } else {
                LocalMedia media = adapter.getItem(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        Intent intent = new Intent(RebllionCommitActivity.this, PictureExternalPreviewActivity.class);
                        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) selectList);
                        intent.putExtra(PictureConfig.EXTRA_POSITION, position);
                        intent.putExtra(PictureConfig.DIRECTORY_PATH, "/custom_file");
                        startActivityForResult(intent, REQUEST_CODE);
                        overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(RebllionCommitActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(RebllionCommitActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        }
    };

    OnItemInternalClick onLongClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (isLongClick) {
                adapter.setEdting(true);
                isLongClick = false;
            } else {
                adapter.setEdting(false);
                isLongClick = true;
            }
        }
    };

    @Override
    public void getRemainListSize(List<LocalMedia> list) {
        selectList = list;
        currentList = list;
        adapter.notifyDataSetChanged();
    }

    public void uploadData() {
        showProgress(getString(R.string.rebllion_publish_wait), false);

        if (currentList.size() > 0) {
            List<String> picList = new ArrayList<>();
            switch (PictureMimeType.pictureToVideo(currentList.get(0).getPictureType())) {
                case 1:
                    for (int i = 0; i < currentList.size(); i++) {
                        if (TextUtils.isEmpty(currentList.get(i).getCompressPath())) {
                            picList.add(currentList.get(i).getPath());
                        } else {
                            picList.add(currentList.get(i).getCompressPath());
                        }

                    }


                    mCallback.setInt1(1);
                    break;
                case 2:
                    mVideoCoverImage = getFirstFrameFromVideo(currentList.get(0).getPath());
                    if (TextUtils.isEmpty(mVideoCoverImage)) {
                        closeProgress();
                        toast(R.string.rebllion_publish_video_cover_path_empty);
                        return;
                    }

                    picList.add(mVideoCoverImage);
                    mCallback.setInt1(2);
                    mCallback.setObj(currentList.get(0).getPath());
                    break;
            }
            NetUtils.getNetAdapter().uploadImages(getOwnerName(), picList, mCallback);
            return;
        }

        publish(null, null);
    }

    private void publish(SingleResult singleResult, Object videoCoverImage) {
        FUsers fUsers = UserManager.getInstance().getUser();
        ParamsEditor pe = new ParamsEditor();
        pe.put("userId", fUsers.getUserId());
        pe.put("discloseType", rebellionType);
        pe.put("contentText", rebllion_commit.getText().toString());
        if (mLocationState == 0 || mLocationState == 2) {
            addree_cv.setText("");
        }
        pe.put("location", addree_cv.getText().toString());
        pe.put(Constances.SITE_NET_KEY, Constances.SITE_ID);

        pe.put("contentImages", singleResult == null || singleResult.getImages() == null ? "" : singleResult.getImages().toString());
        pe.put("contentVideo", singleResult == null || TextUtils.isEmpty(singleResult.getVideoUrl()) ? "" : singleResult.getVideoUrl());
        if (images != null) {
            coverImageUrl = images.get(0).getAsJsonObject().get("imageUrl").getAsString();
        }
        pe.put("coverImage", TextUtils.isEmpty(coverImageUrl) ? "" : coverImageUrl);
        pe.put(Constances.SITE_NET_KEY, SITE_ID);
        mCallback.setInt1(-1);
        NetUtils.getNetAdapter().postRebellion(getOwnerName(), pe.getEncryptedParams(fUsers.getToken()), mCallback);
    }

    AbsNetCallBack mCallback = new AbsNetCallBack<SingleResult>(SingleResult.class) {
        @Override
        public void onSuc(SingleResult singleResult) {
            if (singleResult == null || !singleResult.isSuccess() ||
                    (getInt1() == 1 && singleResult.getImages() == null) ||
                    (getInt1() == 2 && (singleResult.getImages() == null || !singleResult.getImages().toString().contains("imageUrl"))) ||
                    (getInt1() == 3 && TextUtils.isEmpty(singleResult.getVideoUrl()))) {
//                onError(null, null);
                return;
            }

            if (getInt1() == 2) {
                String videoUrl = getObj().toString();
                mCallback.setInt1(3);
                images = singleResult.getImages();
                mCallback.setObj(singleResult.getImages().toString());
                deleteVideoCoverImage();
                NetUtils.getNetAdapter().uploadVideo(getOwnerName(), videoUrl, mCallback);
                return;
            }

            if (getInt1() == -1) {
                toast(R.string.rebllion_publish_succ);
                finish();
                return;
            }

            if (getInt1() == 1 || getInt1() == 3) {
                //getInt1为1时getObj为空
                publish(singleResult, getObj());
                return;
            }
        }

        @Override
        public void onError(Throwable ex, String errorMsg) {
            toast(R.string.rebllion_publish_failure);
            closeProgress();

            if (getInt1() == 2) {
                deleteVideoCoverImage();
            }
        }

        @Override
        public void onEnd() {
            if (getInt1() == -1) {
                closeProgress();
            }
        }
    };

    private void deleteVideoCoverImage() {
        if (!TextUtils.isEmpty(mVideoCoverImage)) {
            File file = new File(mVideoCoverImage);
            if (file.exists()) {
                file.delete();
                mVideoCoverImage = null;
            }
        }
    }

    private String getFirstFrameFromVideo(String videoPath) {
        //获取第一帧图像的bitmap对象
        Bitmap bitmap;
        try {
            MediaMetadataRetriever media = new MediaMetadataRetriever();
            media.setDataSource(videoPath);
            bitmap = media.getFrameAtTime();
            media.release();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        File f = new File(Environment.getExternalStorageDirectory().getPath() + PictureFileUtils.CAMERA_PIC_PATH, "CoverCut_" + System
                .currentTimeMillis() + ".jpeg");
        if (f.exists()) {
            f.delete();
        } else if (!f.getParentFile().exists()) {
            f.getParentFile().mkdir();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            return f.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private void getLocation() {
        mLocationState = 0;
        refreshLocationState(null);
        if (SystemClock.elapsedRealtime() - mLocationTime >= 1000) {
            if (mLocationClient != null) {
                mLocationClient.start();
            }
            mLocationTime = SystemClock.elapsedRealtime();
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mLocationClient != null) {
                        mLocationClient.start();
                    }
                    mLocationTime = SystemClock.elapsedRealtime();
                }
            }, 1000);
        }
    }

    private void locatingFailed(String errorStr) {
        toast(errorStr);
        mLocationState = 2;
        refreshLocationState(null);
    }

    private void refreshLocationState(String location) {
        switch (mLocationState) {
            case 0:
                addree_cv.setText(R.string.rebllion_publish_locating);
                break;
            case 1:
                addree_cv.setText(location);
                break;
            case 2:
                addree_cv.setText(R.string.rebllion_publish_locating_failed);
                break;
        }
    }

    private void checkLocationPermission() {
        mPermissionUtils = new PermissionUtils(this);
        mPermissionUtils.addPermission(Manifest.permission.READ_PHONE_STATE);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_FINE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        mPermissionUtils.addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        mPermissionUtils.setPermissionListener(new PermissionUtils.PermissionListener() {
            @Override
            public void onUserRefusesPermissions() {
                locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
            }
        });

        if (mPermissionUtils.checkAndRequestPermissions()) {
            initLocation();
            getLocation();
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.PERMISSIONS_REQUEST_CODE) {
            String msg = "本页面的定位功能需要用到以下权限：\n1. 读取手机状态\n2. 获取位置信息（基站）\n3. 获取位置信息（GPS）\n4. 读取手机存储的信息\n5. 写入信息到手机存储\n\n请授予这些权限确保定位功能可以正常运行。";
            if (mPermissionUtils.recheckPermissions(grantResults, msg)) {
                initLocation();
                getLocation();
            }
        }
    }

    private void initLocation() {
        if (mLocationClient != null) {
            return;
        }
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(mLocationListener);

        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(0);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps
        option.setLocationNotify(false);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
//        option.SetWifiValidTime(5*60*1000);
        //可选，7.2版本新增能力，如果您设置了这个接口，首次启动定位时，会先判断当前WiFi是否超出有效期，超出有效期的话，会先重新扫描WiFi，然后再定位

        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy() {
        if (mLocationClient != null) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(mLocationListener);
        }
        super.onDestroy();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        int length = getStrLength(s.toString());
        if (length == 120) {
            toast(R.string.only_120_word);
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == BDLocation.TypeGpsLocation) {
                //当前为GPS定位结果，可获取以下信息
//                location.getSpeed();    //获取当前速度，单位：公里每小时
//                location.getSatelliteNumber();    //获取当前卫星数
//                location.getAltitude();    //获取海拔高度信息，单位米
//                location.getDirection();    //获取方向信息，单位度
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                //当前为网络定位结果，可获取以下信息
//                location.getOperators();    //获取运营商信息
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                //当前为网络定位结果
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                //当前网络定位失败
                //可将定位唯一ID、IMEI、定位失败时间反馈至loc-bugs@baidu.com
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                //当前网络不通
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                //当前缺少定位依据，可能是用户没有授权，建议弹出提示框让用户开启权限
                //可进一步参考onLocDiagnosticMessage中的错误返回码
            }

            String locationStr;

            //获取定位结果
//            location.getTime();    //获取定位时间
//            location.getLocationID();    //获取定位唯一ID，v7.2版本新增，用于排查定位问题
//            location.getLocType();    //获取定位类型
//            location.getLatitude();    //获取纬度信息
//            location.getLongitude();    //获取经度信息
//            location.getRadius();    //获取定位精准度
//            location.getAddrStr();    //获取地址信息
//            location.getCountry();    //获取国家信息
//            location.getCountryCode();    //获取国家码
            if (TextUtils.isEmpty(location.getCity()) || TextUtils.isEmpty(location.getDistrict())) {
                locatingFailed("获取定位失败，未知错误");
                return;
            }
            locationStr = location.getCity() + "-";    //获取城市信息
//            location.getCityCode();    //获取城市码
            locationStr += location.getDistrict();    //获取区县信息
//            location.getStreet();    //获取街道信息
//            location.getStreetNumber();    //获取街道码
//            location.getLocationDescribe();    //获取当前位置描述信息
//            location.getPoiList();    //获取当前位置周边POI信息
//
//            location.getBuildingID();    //室内精准定位下，获取楼宇ID
//            location.getBuildingName();    //室内精准定位下，获取楼宇名称
//            location.getFloor();    //室内精准定位下，获取当前位置所处的楼层信息

            mLocationState = 1;
            refreshLocationState(locationStr);
            if (mLocationClient != null) {
                mLocationClient.stop();
            }
        }

        /**
         * 回调定位诊断信息，开发者可以根据相关信息解决定位遇到的一些问题
         * 自动回调，相同的diagnosticType只会回调一次
         *
         * @param locType           当前定位类型
         * @param diagnosticType    诊断类型（1~9）
         * @param diagnosticMessage 具体的诊断信息释义
         */
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_GPS) {
                //建议打开GPS
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_BETTER_OPEN_WIFI) {
                //建议打开wifi，不必连接，这样有助于提高网络定位精度！
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_LOC_PERMISSION) {
                //定位权限受限，建议提示用户授予APP定位权限！
                locatingFailed("获取定位失败，请检查APP是否有定位权限");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CHECK_NET) {
                //网络异常造成定位失败，建议用户确认网络状态是否异常！
                locatingFailed("获取定位失败，请检查网络是否通畅以及GPS开关是否打开");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_CLOSE_FLYMODE) {
                //手机飞行模式造成定位失败，建议用户关闭飞行模式后再重试定位！
                locatingFailed("获取定位失败，请检查网络是否通畅以及GPS开关是否打开");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_INSERT_SIMCARD_OR_OPEN_WIFI) {
                //无法获取任何定位依据，建议用户打开wifi或者插入sim卡重试！
                locatingFailed("获取定位失败，请检查网络是否通畅以及GPS开关是否打开");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_NEED_OPEN_PHONE_LOC_SWITCH) {
                //无法获取有效定位依据，建议用户打开手机设置里的定位开关后重试！
                locatingFailed("获取定位失败，请检查网络是否通畅以及GPS开关是否打开");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_SERVER_FAIL) {
                //百度定位服务端定位失败
                //建议反馈location.getLocationID()和大体定位时间到loc-bugs@baidu.com
                locatingFailed("获取定位失败，未知错误");
            } else if (diagnosticType == LocationClient.LOC_DIAGNOSTIC_TYPE_FAIL_UNKNOWN) {
                //无法获取有效定位依据，但无法确定具体原因
                //建议检查是否有安全软件屏蔽相关定位权限
                //或调用LocationClient.restart()重新启动后重试！
                locatingFailed("获取定位失败，未知错误");
            }
        }
    }
}
